#define _CRT_SECURE_NO_WARNINGS 1
#include "SList.h"

void SLPrint(SLNode* phead)
{
	SLNode* pcur = phead;
	while (pcur != NULL)
	{
		printf("%d -> ", pcur->data);
		pcur = pcur->next;
	}
	printf("NULL\n");
}

SLNode* SLBuyNode(SLDataType x)
{
	SLNode* node = (SLNode*)malloc(sizeof(SLNode));
	assert(node != NULL);
	node->data = x;
	node->next = NULL;
	return node;
}

void SLPushBack(SLNode** pphead, SLDataType x)
{
	SLNode* node = SLBuyNode(x);
	if (*pphead == NULL)
	{
		*pphead = node;
		return;
	}
	SLNode* pcur = *pphead;
	while (pcur->next != NULL)
	{
		pcur = pcur->next;
	}
	pcur->next = node;
	node->next = NULL;
}

void SLPushFront(SLNode** pphead, SLDataType x)
{
	SLNode* node = SLBuyNode(x);
	if (*pphead == NULL)
	{
		*pphead = node;
		return;
	}
	node->next = *pphead;
	*pphead = node;
}

void SLPopBack(SLNode** pphead)
{
	assert(pphead);
	assert(*pphead);
	if ((*pphead)->next==NULL)
	{
		free(*pphead);
		*pphead = NULL;
		return;
	}
	SLNode* pcur = NULL;
	SLNode* ptail = *pphead;
	while (ptail->next != NULL)
	{
		pcur = ptail;
		ptail = ptail->next;
	}
	pcur->next = ptail->next;
	free(ptail);
	ptail = NULL;
}

void SLPopFront(SLNode** pphead)
{
	assert(pphead);
	assert(*pphead);
	SLNode* pcur = *pphead;
	*pphead = (*pphead)->next;
	free(pcur);
	pcur = NULL;
}

SLNode* SLFind(SLNode** pphead, SLDataType x)
{
	assert(pphead);
	assert(*pphead);
	SLNode* pcur = *pphead;
	while (pcur != NULL)
	{
		if (pcur->data==x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}

void SLInsert(SLNode** pphead, SLNode* pos,SLDataType x)
{
	assert(pphead);
	assert(*pphead);
	assert(pos);
	SLNode* node = SLBuyNode(x);
	if (pos == *pphead)
	{
		node->next = *pphead;
		*pphead = node;
		return;
	}
	SLNode* pcur = *pphead;
	while (pcur->next != pos)
	{
		pcur = pcur->next;
	}
	pcur->next = node;
	node->next = pos;
}

void SLInsertAfter(SLNode** pphead, SLNode* pos, SLDataType x)
{
	assert(pphead);
	assert(*pphead);
	assert(pos);
	SLNode* node = SLBuyNode(x);
	node->next = pos->next;
	pos->next = node;
}

void SLErase(SLNode** pphead, SLNode* pos)
{
	assert(pphead);
	assert(*pphead);
	assert(pos);
	SLNode* pcur = *pphead;
	if (pos == *pphead)
	{
		*pphead = pos->next;
		free(pos);
		pos = NULL;
		return;
	}
	while (pcur->next != pos)
	{
		pcur = pcur->next;
	}
	pcur->next = pos->next;
	free(pos);
	pos = NULL;
}

void SLEraseAfter(SLNode** pphead, SLNode* pos)
{
	assert(pos && pos->next);
	assert(pphead);
	assert(*pphead);
	SLNode* pcur = pos->next;
	pos->next = pcur->next;
	free(pcur);
	pcur = NULL;
}

void SLDestroy(SLNode** pphead)
{
	assert(pphead);
	assert(*pphead);
	SLNode* pcur = *pphead;
	while (pcur != NULL)
	{
		SLNode* next = pcur->next;
		free(pcur);
		pcur = next;
	}
	*pphead = NULL;
}